<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="数据名">
              <el-select v-model="queryParams.masterIds" placeholder="请选择数据名" clearable multiple collapse-tags
                filterable>
                <template #header>
                  <el-button-group>
                    <el-button v-for="item in masterQueryButtonParas" :key="item.key"
                      @click="handleMasterQuickSelect(item)" :type="item.type" @mouseenter="masterSelMouseEnter(item)"
                      :size="item.size">{{ item.value }}</el-button>
                  </el-button-group>
                </template>
                <el-option v-for="item in kpiMasterList" :key="item.id" :label="item.name" :value="item.id">
                  <span>{{ item.name }}</span>
                  <span style="float:center; color: #8492a6; margin-left: 10px;">{{ item.dataCategory }}</span>
                  <span style="float:right; color: #8492a6; margin-left: 10px;">{{ getPlantLabelByMasterId(item.id)
                    }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年份" prop="yearNum">
              <el-input v-model="queryParams.yearNum" placeholder="请输入年份" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="月份" prop="monthNum">
              <el-input-number v-model="queryParams.monthNum" placeholder="请输入月份" :min="1" :max="12" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="周" prop="weekNum">
              <el-input-number v-model="queryParams.weekNum" placeholder="请输入周" :min="1" :max="54" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="日期" prop="byDaily">
              <el-date-picker clearable v-model="queryParams.byDaily" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择日期" />
            </el-form-item>
            <el-form-item label="班次" prop="byShift">
              <el-select v-model="queryParams.byShift" placeholder="请选择班次" clearable>
                <el-option v-for="item in shiftList" :key="item.key" :label="item.value" :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['manu:kpiRecord:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['manu:kpiRecord:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['manu:kpiRecord:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Pointer" @click="handleDefault"
              v-hasPermi="['manu:kpiRecord:edit']">默认</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="kpiRecordList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="数据名" align="center" prop="masterId" width="500">
          <template #default="scope">
            <el-row>
              <el-col :span="12">
                <span>{{ getMasterById(scope.row.masterId)?.name }}</span>
              </el-col>
              <el-col :span="8">
                <el-tag type="warning">{{ getPlantLabelByMasterId(scope.row.masterId) }}</el-tag>
              </el-col>
              <el-col :span="4">
                <el-tag :type="getMasterById(scope.row.masterId).dataCategory == 'actual' ? 'primary' : 'success'">{{
                  getMasterById(scope.row.masterId).dataCategory
                }}</el-tag>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="年份" align="center" prop="yearNum" width="80" />
        <el-table-column label="时间" align="center">
          <template #default="scope">
            <span>{{ getDatePreferenceByRecord(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据结果" align="center" prop="kpiResult" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['manu:kpiRecord:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['manu:kpiRecord:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="kpiRecordFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据结果" prop="kpiResult">
          <el-input v-model="form.kpiResult" placeholder="请输入数据结果" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="KpiRecord" lang="ts">
import { listKpiRecord, getKpiRecord, delKpiRecord, addKpiRecord, updateKpiRecord, setKpiRecordAsDefault } from '@/api/manu/kpiRecord';
import { KpiRecordVO, KpiRecordQuery, KpiRecordForm } from '@/api/manu/kpiRecord/types';
import { listKpiMaster } from '@/api/manu/kpiMaster';
import { KpiMasterVO } from '@/api/manu/kpiMaster/types';

interface shiftVO {
  key: number;
  value: string;
}

interface plantVo {
  key: string;
  value: string;
  type: string;
}

interface masterQueryButtonPara {
  label: string;
  type: string;
  value: string;
  size: string;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const kpiRecordList = ref<KpiRecordVO[]>([]);
const kpiMasterList = ref<KpiMasterVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const plantOrgList = reactive<plantVo[]>([
  { key: 'plant', value: '工厂', type: '1' },
  { key: 'bv', value: 'BV', type: '2' },
  { key: 'hm', value: 'HM', type: '2' },
]);

const masterQueryButtonParas = reactive<masterQueryButtonPara[]>([]);
const shiftList = reactive<shiftVO[]>([
  { key: 1, value: '白班' },
  { key: 2, value: '中班' }
]);



const queryFormRef = ref<ElFormInstance>();
const kpiRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: KpiRecordForm = {
  id: undefined,
  masterId: undefined,
  yearNum: undefined,
  monthNum: undefined,
  weekNum: undefined,
  byDaily: undefined,
  byShift: undefined,
  kpiResult: undefined
}
const data = reactive<PageData<KpiRecordForm, KpiRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    masterId: undefined,
    yearNum: undefined,
    monthNum: undefined,
    weekNum: undefined,
    byDaily: undefined,
    byShift: undefined,
    kpiResult: undefined,
    masterIds: [],
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    masterId: [
      { required: true, message: "主数据主键不能为空", trigger: "blur" }
    ],
    kpiResult: [
      { required: true, message: "数据结果不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

const getPlantLabelByMasterId = (masterId: string | number) => {
  const master = kpiMasterList.value.find(item => item.id == masterId);
  return plantOrgList.find(item => item.key == master?.scope)?.value;
}

/** 主数据快速查询按钮 相关的方法*/
const masterSelMouseEnter = (item: masterQueryButtonPara) => {
  masterQueryButtonParas.forEach(button => {
    button.type = 'info';
    button.size = 'small';
  });
  let indexNum = masterQueryButtonParas.findIndex(button => button.value == item.value)
  masterQueryButtonParas[indexNum].type = 'primary';
  masterQueryButtonParas[indexNum].size = 'large';
}

const handleMasterQuickSelect = (item: masterQueryButtonPara) => {
  queryParams.value.masterIds = []
  kpiMasterList.value.forEach(master => {
    let group = JSON.parse(master.screCode).category;
    if (group.includes(item.value)) {
      if (!queryParams.value.masterIds.includes(master.id)) {
        queryParams.value.masterIds.push(master.id);
      }
    }
  });
}



const getMasterById = (id: string | number) => {
  return kpiMasterList.value.find(item => item.id == id);
}

/**
 * data tabel reference
 */

const getDatePreferenceByRecord = (record: KpiRecordVO) => {
  if (record.byShift) {
    return `${record.byDaily.substring(5, 10)}, ${shiftList.find(shift => shift.key == record.byShift).value}`;
  } else
    if (record.byDaily) {
      return record.byDaily.substring(5, 10);
    } else if (record.weekNum) {
      return `第${record.weekNum}周`;
    } else if (record.monthNum) {
      return `${record.monthNum}月`;
    } else if (record.yearNum) {
      return `${record.yearNum}年`;
    }
}


/** 查询记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listKpiRecord(queryParams.value);
  kpiRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  kpiRecordFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.masterIds = [];
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: KpiRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加记录";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: KpiRecordVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getKpiRecord(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改记录";
}

/** 提交按钮 */
const submitForm = () => {
  kpiRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateKpiRecord(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addKpiRecord(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: KpiRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delKpiRecord(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('manu/kpiRecord/export', {
    ...queryParams.value
  }, `kpiRecord_${new Date().getTime()}.xlsx`)
}

/** 默认按钮操作 */
const handleDefault = async () => {
  const _ids = Object.values(ids.value);
  await proxy?.$modal.confirm('是否确认将选中的' + _ids.length + '项数据设为默认值？').finally(() => loading.value = false);
  const selectedRecords = kpiRecordList.value.filter(record => _ids.includes(record.id));
  const selectedRecordsWithoutResult = selectedRecords.filter(record => !record.kpiResult);
  if (selectedRecordsWithoutResult.length == selectedRecords.length) {
    await setKpiRecordAsDefault(_ids)
  } else {
    await proxy?.$modal.confirm(selectedRecords.length - selectedRecordsWithoutResult.length + '条数据已被赋值，将不会对其进行自动赋值，是否继续？').finally(() => loading.value = false);
    await setKpiRecordAsDefault(_ids)
  }
  await getList();
}

onBeforeMount(async () => {
  const res = await listKpiMaster({ pageNum: 1, pageSize: 1000 });
  kpiMasterList.value = res.rows;
  
  let masterGroups: string[] = [];
  res.rows.forEach(master => {
    let group = JSON.parse(master.screCode).category;
    group.forEach((item: string) => {
      if (!masterGroups.includes(item)) {
        masterGroups.push(item);
        masterQueryButtonParas.push({ label: item, type: 'info', value: item, size: 'small' });
      }
    });
  });

});

onMounted(() => {
  getList();

});
</script>
